﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AMS.DeDuplicator.CommonLayer.Iterator;

namespace AMS.DeDuplicator.CommonLayer.Adapter
{
    // adapt an Enumerator to an Iterator
    public class EnumeratorAdapter<T> : IIterator<T>
    {
        List<T> _items;
        int _currentIndex;

        public EnumeratorAdapter(IEnumerator<T> enumerator)
        {
            InputValidator.ValidateNotNull(enumerator);

            _items = new List<T>();
            PopulateItems(enumerator);
            _currentIndex = -1;
        }

        private void PopulateItems(IEnumerator<T> enumerator)
        {
            while (enumerator.MoveNext())
            {
                _items.Add(enumerator.Current);
            }
        }

        public bool HasNext()
        {
            // no way to tell HasNext on IEnumerator without causing it to move
            return _currentIndex < _items.Count - 1;
        }

        public T GetNext()
        {
            if (!HasNext())
                ExceptionHandler.NoNextException();

            _currentIndex++;
            return _items[_currentIndex];
        }
    }
}
